package com.example.utils;

import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @className: RsaUtils
 * @description: RSA加密工具类
 * @date: 2024/7/26 下午2:28
 * @author: gqd
 * @version: 1.0
 */
public class RsaUtils {

     /**
      * 签名算法名称
      */
    private static final String RSA_KEY_ALGORITHM = "RSA";

    /**
     * RSA公钥加密
     */
    public static String encrypt(String context) {
        try {
            // 获取公钥数据，publickey可以存入文件中，也可以通过接口获取，目前是存入文件中
            String publicKey = new String(Files.readAllBytes(Paths.get("src/main/resources/pbk.txt")));
            
            // base64编码公钥
            byte[] decoded = Base64.getDecoder().decode(publicKey.replaceAll(" ", ""));

            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(RSA_KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
            // RSA加密
            Cipher cipher = Cipher.getInstance(RSA_KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(context.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}